<?php
// +----------------------------------------------------------------------------
// | Author: guanhanwen
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
 * 社群
 +------------------------------------------------------------------------------
 * @since 2015-2-26
 +------------------------------------------------------------------------------
 */
namespace Home\Controller;
use Think\Controller;

class TopicController extends Controller {
	
	
	private $AppID = APP_ID;//微信AppID
	private $secret = SECRET;//微信secret
	private $host = '';//当前文件访问地址（一般需动态获取）
	
	
	/**
	 * @todo 初始化
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
	public function _initialize(){
		$this->assign('download_url',DOWNLOAD_URL);
// 		dump($share_data);die;
	}
	/**
	 * @todo 话题详细页
	 * @since 2015-2-26
	 * @author guanhanwen
	 */
    public function index(){
		$this->host = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    	$topic_id = (int)I('get.topic_id');
    	if($topic_id <= 0){
    		$this->error('请勿非法访问！');
    	}
    	$result = D('Guan')->getTopic($topic_id);
    	// dump($result);die;
    	if($result['result'] != 0){
    		$this->error($result['msg']);
    	}
    	$this->assign('topic_info',$result['data']);
    	$share_data = array(
    			'title'=> $result['data']['title'],
//     			'desc' => $result['data']['content'],
    			'desc' => "来自".$result['data']['community_name'],
    			'link' => SHARE_HOST.'/Topic/index?topic_id='.$topic_id,
    			'img_url' => SHARE_HOST.'/Public/Home/images/logo300.jpg'
    	);
		//判断公司职位都不存在就不显示括号
		if(!$result['data']['user']['user_company'] && !$result['data']['user']['user_job']){
			$this->assign('null_job',1);
		}
		$this->assign('host',SHARE_HOST);
    	$this->assign('share_data',$share_data);
    	$this->share();
		$this->display('index');
    }

    /**
     * @todo 话题评论列表
     * @since 2015-2-26
     * @author guanhanwen
     */
    public function ajaxGetTopicCommentList(){
    	$topic_id = I('get.topic_id');
    	$list_last_id = I('get.list_last_id');
    	$result = D('Guan')->getTopicCommentList($topic_id,$list_last_id);

    	if($result['result'] == 2 || $result['result'] == 1){
    		$this->assign('more',0);
    		if($list_last_id <= 0){
    			$this->assign('notice',$result['msg']);
    		}
    	}elseif($result['result'] == 0){
    		$this->assign('more',1);
    		$list = $result['data'];
// dump($list);die;
    		$row_number = count($list);
    		//用于计算是否为最后一页
    		$this->assign('row_number',$row_number);
    		$last_id = $list[$row_number-1]['comment_id'];
    		//已认证
    		$this->assign('count',$result['count']);
    		$this->assign('last_id',$last_id);
    		$this->assign('list',$list);
    	}else{
    		$this->assign('notice',$result['msg']);
    	}
    	// dump($list);die;
    	$this->display('ajax_comment_list');
    }
    
    
    
    /**
     * @todo 写错误日志
     */
    public function writeErrLog($errorMes, $file_name = '') {
    	if(empty($errorMes)) {
    		return false;
    	}
    	//目录不存在就创建
    	if (!file_exists (dirname($file_name))) {
    		if (!@mkdir (dirname($file_name), 0777)) {
    			die($file_name.'目录创建失败！');
    		}
    	}
    	$msg = date('Y-m-d H:i:s').' >>> '.$errorMes.'\r\n';
    	file_put_contents($file_name,$msg,FILE_APPEND);
    }

    public function share(){
    	//签名：将jsapi_ticket、noncestr、timestamp、分享的url按字母顺序连接起来，进行sha1加密，做为签名。
    	$timestamp = time();//当前时间戳。
    	$nonceStr = $this->getRandChar(10);//任意字符串。
    	$ticket = $this->wx_get_jsapi_ticket();

    	$ori = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",$ticket, $nonceStr, $timestamp,$this->host);
    	$sha1 = sha1($ori);//对str串做sha1加密，
    	$this->assign('AppID',$this->AppID);//AppID
    	$this->assign('timestamp',$timestamp);//时间戳
    	$this->assign('nonceStr',$nonceStr);//任意字符串
// dump($sha1);die;
    	$this->assign('sha1',$sha1);//签名
//     	$this->display('share');
    }
    
    //获取token
    public function wx_get_token() {
    	$token = S('access_token');
    	// 通过此接口返回的token的有效期目前为2小时。令牌失效后，JS-SDK也就不能用了。
    	// 因此，这里将token值缓存起来（小于2小时）。缓存失效后，再从接口获取新的token
    	// 这样就可以避免token失效（当然如必要，也可以写入数据库中）
    	if (!$token) {
    		$res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->secret
    		);
    		// 不能频繁的访问https://api.weixin.qq.com/cgi-bin/token，每日有次数限制（一般为2000次）
    		$res = json_decode($res, true);
    		$token = $res['access_token'];
    		S('access_token', $token, 3600);//缓存1小时
    	}
    	return $token;
    	//注意：返回的access_token长度至少要留够512字节
    }
    
    
    //获取jsapi的ticket。
    //jsapi_ticket是公众号用于调用微信JS接口的临时票据，jsapi_ticket有效期7200秒
    public function wx_get_jsapi_ticket(){
    	$ticket = "";
    	do{
    		$ticket = S('wx_ticket');
    		if (!empty($ticket)) {
    			break;
    		}
    		$token = S('access_token');
    		if (empty($token)){
    			$this->wx_get_token();//获取token
    		}
    		$token = S('access_token');
    		if (empty($token)) {
    			break;
    		}
    		$url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
    				$token);
    		$res = file_get_contents($url2);
    		$res = json_decode($res, true);
    		$ticket = $res['ticket'];
    		// 注意：这里需要将获取到的ticket缓存起来（或写到数据库中）
    		// ticket和token一样，不能频繁的访问接口来获取，在每次获取后，我们把它保存起来。
    		S('wx_ticket', $ticket, 3600);
    	}while(0);
    	return $ticket;
    }
    
    //生成随机字符串
    public function getRandChar($length){
    	$str = "";
    	$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    	$max = strlen($strPol)-1;
    
    	for($i=0;$i<$length;$i++){
    		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    	}
    	return $str;
    }
}


 
 